import React, { Component } from 'react';
import MoviesTable from './moviesTable';
import ListGroup from './common/listgroup';
import Pagination from './common/pagination';
import { getMovies } from '../api/services/fakeMovieService';
import { getGenres } from '../api/services/fakeGenreService';
import { paginate } from './utils/paginate';
import _ from 'lodash';
class Movies extends Component {
  state = {
    movies: [],
    genres: [],
    currentPage: 1,
    pageSize: 4,
    sortColumn: {
      path: 'title',
      order: 'asc',
    },
  };

  componentDidMount() {
    const genres = [{ name: '全部' }, ...getGenres()];
    this.setState({
      movies: getMovies(),
      genres,
    });
  }

  handleDelete = (movie) => {
    console.log(movie);
    // 返回一个新的数组, 除过传入的id的这条数据
    const movies = this.state.movies.filter((m) => m._id !== movie._id);
    this.setState({
      movies,
    });
  };

  /**
   * 点击喜欢
   */
  handleLike = (movie) => {
    console.log('已点击');
    console.log(movie);
    //克隆一份原数组
    const movies = [...this.state.movies];
    //拿到下标
    const index = movies.indexOf(movie);
    console.log(index);
    movies[index] = { ...movies[index] };
    movies[index].liked = !movies[index].liked;
    this.setState({
      movies,
    });
  };

  /**
   * 得到用户所选的分类
   * 当用户切到分页第二页再切换分类时，别的选项也会在第二页，
   * 所以需要切换分页到第一页
   */
  handleGenreSelect = (genre) => {
    console.log(genre);
    this.setState({
      selectedGenre: genre,
      currentPage: 1,
    });
  };

  handlePageChange = (page) => {
    this.setState({
      currentPage: page,
    });
  };

  handleSort = (sortColumn) => {
    this.setState({
      sortColumn,
    });
  };
  render() {
    const { length: count } = this.state.movies;
    const {
      pageSize,
      currentPage,
      sortColumn,
      selectedGenre,
      movies: allMovies,
    } = this.state;

    //大于0就进行分页
    //有选项和id才进行筛选
    const getPagedData = () => {
      const filtered =
        selectedGenre && selectedGenre._id
          ? allMovies.filter((m) => m.genre._id === selectedGenre._id)
          : allMovies;
      //排序
      const sorted = _.orderBy(filtered, [sortColumn.path], [sortColumn.order]);
      //分页
      const movies = paginate(sorted, currentPage, pageSize);

      return {
        totalCount: filtered.length,
        data: movies,
      };
    };
    if (count === 0) return <p>暂无数据</p>;
    const { totalCount, data: movies } = getPagedData();
    return (
      <div className="row">
        <div className="col-2">
          <ListGroup
            items={this.state.genres}
            selectedItem={this.state.selectedGenre}
            onItemSelect={this.handleGenreSelect}
          />
        </div>
        <div className="col">
          <p>电影数量: {totalCount}</p>
          <MoviesTable
            movies={movies}
            onLike={this.handleLike}
            onDelete={this.handleDelete}
            onSort={this.handleSort}
            sortColumn={sortColumn}
          />
          <Pagination
            itemsCount={totalCount}
            pageSize={pageSize}
            currentPage={currentPage}
            onPageChange={this.handlePageChange}
          />
        </div>
      </div>
    );
  }
}
export default Movies;
